package com.mai4j.maiadmin.controller.api.system;

import com.github.wnameless.json.flattener.JsonFlattener;
import com.github.wnameless.json.unflattener.JsonUnflattener;
import com.google.gson.Gson;
import com.mai4j.maiadmin.model.RespCode;
import com.mai4j.maiadmin.model.dto.SettingKVDTO;
import com.mai4j.maiadmin.model.http.SettingGetReq;
import com.mai4j.maiadmin.model.http.SettingSaveReq;
import com.mai4j.maiadmin.model.http.response.SettingGetResp;
import com.mai4j.maiadmin.model.http.response.SimpleResp;
import com.mai4j.maiadmin.model.vo.SettingVO;
import com.mai4j.maiadmin.service.SettingService;
import com.mai4j.maiadmin.support.I18nProvider;
import com.mai4j.maiadmin.support.security.aop.annotation.RequiresAuthentication;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@RequiresAuthentication
@RestController
@RequestMapping("/api/system/setting")
public class ApiSettingController {

    private final SettingService settingService;

    public ApiSettingController(SettingService settingService) {
        this.settingService = settingService;
    }

    @PostMapping("/save")
    public ResponseEntity<SimpleResp> save(@RequestBody @Validated SettingSaveReq settingSaveReq) {
        settingService.save("config",
                new SettingKVDTO()
                        .put(JsonFlattener.flattenAsMap(new Gson().toJson(settingSaveReq)))); // 展平
        return ResponseEntity.ok(new SimpleResp()
                .setCode(RespCode.OK.getCode())
                .setMessage(I18nProvider.get("text.save.successfully")));
    }

    /**
     * 获取全部系统配置
     *
     * @param settingGetReq settingGetReq
     * @return 权限
     */
    @PostMapping("/get")
    public ResponseEntity<SettingGetResp> get(@RequestBody @Validated SettingGetReq settingGetReq) {
        SettingKVDTO settingKVDTO = settingService.get(settingGetReq.getCode());
        return ResponseEntity.ok(new SettingGetResp()
                .setSetting(settingKVDTO.isEmpty() ? null : new Gson().fromJson(JsonUnflattener.unflatten(settingKVDTO), SettingVO.class))
                .setCode(RespCode.OK.getCode())
                .setMessage(I18nProvider.get("text.successfully")));
    }
}
